using System;
using System.IO;
using Script.Map;
using UnityEngine;

public class MapCreator : MonoBehaviour
{
	[Serializable]
	public class Bound
	{
		public CapsuleCollider2D bottom;

		public CapsuleCollider2D top;

		public CapsuleCollider2D right;

		public CapsuleCollider2D left;
	}

	public Land[] lands;

	[Header("Requirement")]
	public Bound bound;

	public Transform map;

	public Material mapMaterial;

	public static int landId;

	private Land land;

	private StringReader stringReader;

	public void Beginning(string @string)
	{
		stringReader = new StringReader(@string);
		land = lands[landId];
		int[] array = ReadArgs();
		Library.player.SetPosition(new Vector2(array[0] * 2, array[1] * 2));
		array = ReadArgs();
		Map.width = array[0];
		Map.height = array[1];
		Map.grid = new byte[Map.width, Map.height];
		CreateTerrain();
		CreateEnvironment();
		Map.SetGrid();
		SetBounds();
		MushroomController.mushrooms = land.interactiveObjects;
		mapMaterial.SetTexture("_MainTex", land.texture);
		Library.music.Play(SceneName.Game);
		stringReader.Close();
		UnityEngine.Object.Destroy(this);
	}

	private void CreateEnvironment()
	{
		while (stringReader.Peek() != -1)
		{
			int[] array = ReadArgs();
			GameObject original = land.mountain;
			if (array[0] > 0)
			{
				original = ((array[0] > land.food.Length) ? land.environment[array[0] - land.food.Length - 1] : land.food[array[0] - 1]);
			}
			int num = array[1];
			for (int i = 0; i < num; i++)
			{
				array = ReadArgs();
				Transform transform = UnityEngine.Object.Instantiate(original, map).transform;
				transform.position = new Vector3(array[0] * 2, array[1] * 2);
				transform.rotation = Quaternion.Euler(0f, 0f, UnityEngine.Random.value * 360f);
				Map.grid[array[0], array[1]] = 2;
			}
		}
	}

	private void CreateTerrain()
	{
		for (int i = 0; i < Map.width; i++)
		{
			for (int j = 0; j < Map.height; j++)
			{
				Transform transform = UnityEngine.Object.Instantiate(land.grounds[int.Parse(stringReader.ReadLine())], map).transform;
				transform.position = new Vector3(i * 2, j * 2);
			}
		}
	}

	private int[] ReadArgs()
	{
		string[] array = stringReader.ReadLine().Split('\t');
		int[] array2 = new int[array.Length];
		for (int i = 0; i < array.Length; i++)
		{
			array2[i] = int.Parse(array[i]);
		}
		return array2;
	}

	private void SetBounds()
	{
		bound.bottom.offset = new Vector2(Map.width, 0f);
		bound.bottom.size = new Vector2(Map.width * 2, 1f);
		bound.top.offset = new Vector2(Map.width, Map.height * 2);
		bound.top.size = new Vector2(Map.width * 2, 1f);
		bound.right.offset = new Vector2(0f, Map.height);
		bound.right.size = new Vector2(1f, Map.height * 2);
		bound.left.offset = new Vector2(Map.width * 2, Map.height);
		bound.left.size = new Vector2(1f, Map.height * 2);
	}
}
